package com.tis.interfaces.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import promis.utility.CommonService;

import com.tis.database.entitys.security.AdUserLogin;
import com.tis.database.entitys.staging.ApplicationLoging;
import com.tis.database.services.security.IAdUserLoginServices;
import com.tis.encryption.AESencrp;
import com.tis.interfaces.apps.SESSION_MANAGE;
import com.tis.interfaces.controller.commons.CommonController;

@Controller
public class LoginController extends CommonController {
	
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private IAdUserLoginServices iAdUserLoginServices;
	
	@RequestMapping(value="/login", method = RequestMethod.GET)	
	public String Login(HttpServletRequest request, Model model) throws Exception {
		log.info("welcome to mainPage"); 		
		try {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			//Put History 		
			try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
			
			if(UserLoginValidation((request)))
				return "redirect:/index.htm";		
			
		} catch (Exception e) {
			log.error(e.getMessage());
			throw e;
		}
		
		model.addAttribute("loginForm", new LoginForm());
		return "/login/loginform";
	}
	
	@RequestMapping(value="/login", method = RequestMethod.POST)
	public String Security(HttpServletRequest request, Model model,
						   @ModelAttribute("loginForm") @Valid	LoginForm loginForm, 
																BindingResult result) throws Exception {
		try {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			log.info("loginForm.getUsername()=" + loginForm.getUsername() + "// loginForm.getPassword()=" + loginForm.getPassword());  
			HttpSession session = request.getSession();					
			
			if(UserLoginValidation((request)))
				return "redirect:/index.htm";
			
			if(result.hasErrors())
				return "/login/loginform";
			
			AdUserLogin adUserLoin = iAdUserLoginServices.findByUserPassword(AESencrp.encrypt(loginForm.getUsername()), AESencrp.encrypt(loginForm.getPassword()));
			
			if(!CommonService.IsNull(adUserLoin)) {
				log.info("adUserLoin.getUserLogin() = " + adUserLoin.getUserLogin());
				if(AESencrp.decrypt(adUserLoin.getUserLogin()).equals(loginForm.getUsername()) 
						&& AESencrp.decrypt(adUserLoin.getPassword()).equals(loginForm.getPassword()) 
						&& CommonService.IsNullRString(adUserLoin.getIsactive()).equals("Y") 
						&& CommonService.IsNullRString(adUserLoin.getStatus()).equals("A") 
						&& CommonService.IsNullRString(adUserLoin.getIsdeleted()).equals("N"))
				{
					//Step 1 --> Stamp Lasted Computer Access 
					try {UpdateAdUserLogin(request, adUserLoin);}catch(Exception e) {e.printStackTrace();}
					
					//Step 2 --> Keep AduserLogin Object to privtae user session
					session.setAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin, adUserLoin);
					
					//Step 3 --> Put History 
					try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
					
					System.out.println("redirect:/index.htm");
					return "redirect:/index.htm";
				}else
					model.addAttribute("message", "That password is incorrect. Be sure you're using the password for your PROMIS Account.");
			}
			else {
				model.addAttribute("message", "That password is incorrect. Be sure you're using the password for your PROMIS Account.");
				session.setAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin, null);
			}
		}catch(HibernateException e) {
			e.printStackTrace();
			throw e;
		}
		return "/login/loginform";
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.GET) 
	public String LogoutGet(HttpServletRequest request) throws Exception  {
		setCurrentAppsInstanceNo();
		KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
		
		log.info("welcome to LogoutGet");			
		return "redirect:/login.htm";
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.POST)
	public String Logout(HttpServletRequest request) throws Exception{	
		setCurrentAppsInstanceNo();
		KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
		log.info("welcome to Logout"); 		
		//Put History 		
		try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
		
		HttpSession session = request.getSession();
		session.setAttribute(SESSION_MANAGE.SECURITY_PAGE.AdUserLogin, null);		
		
		return "redirect:/login.htm";
	}	
}
